package com.chuanyekeji.aokai.Controller;

import com.chuanyekeji.aokai.Entity.Information;
import com.chuanyekeji.aokai.Entity.Product;
import com.chuanyekeji.aokai.Entity.Search;
import com.chuanyekeji.aokai.Mapper.InformationMapper;
import com.chuanyekeji.aokai.Mapper.ProductMapper;
import com.chuanyekeji.aokai.Util.ReturnData;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
public class SearchController {

    @Autowired
    InformationMapper informationMapper;

    @Autowired
    ProductMapper productMapper;

    /**
     * 查询
     * @param index
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("get_list_by_keyword")
    String search(@RequestParam(required=false,defaultValue="null") String index,
                  @RequestParam(required=false,defaultValue="1") int page,
                  @RequestParam(required=false,defaultValue="6") int rows) {
        //int lastRow = rows * page;
        //int indexRow = lastRow - rows;
        int indexRow = rows * page - rows;
        int lastRow = rows * page - 1;
        List<Search> searchList = new ArrayList<>();
        int total = 0;
        if(!index.equals("null") && index != null) {
            List<Product> productList = productMapper.searchIndex("%" + index + "%");
            List<Information> informationList = informationMapper.searchIndex("%" + index + "%");
            for(Product p : productList) {
                Search s = new Search();
                s.setId(p.getId());
                s.setTitle(p.getProductName());
                s.setType(p.getProductType().getProductTypeName());
                s.setDate(new Date().toString());
                s.setFlat(true);
                searchList.add(s);
            }
            for(Information i : informationList) {
                Search s = new Search();
                s.setId(i.getId());
                s.setTitle(i.getInformationTitle());
                s.setType("资讯");
                s.setDate(i.getCreateTime().toString());
                s.setFlat(false);
                searchList.add(s);
            }
            total = productList.size() + informationList.size();
            if(total > 6) {
                searchList = searchList.subList(indexRow,lastRow);
            }
        } else {
            return ReturnData.success("请键入索引关键字");
        }
        Map<String,Object> data = new HashMap<>();
        data.put("code",1);
        data.put("msg","success");
        data.put("data",searchList);
        data.put("total",total);
        return ReturnData.success("success",data);
    }
}
